﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibriBusinessLogic.MyException;

namespace AteneoLibriBusinessLogic.DAL
{
    public class CityFacade
    {

        AteneoLibriEntityFramework.AteneoLibriEntities db = new AteneoLibriEntityFramework.AteneoLibriEntities();

        public List<City> getCities()
        {
            List<City> cities = new List<City>();
            List<AteneoLibriEntityFramework.City> citiesEF = db.Cities.ToList();

            foreach (var item in citiesEF)
            {
                var city = TOA.CityAssembler.Assembler(item);
                cities.Add(city);
            }

            return cities;
        }


        public City getCity(Guid cityId)
        {
            City city = getCities().Where(x => x.IdCity == cityId).FirstOrDefault();
            return city;
        }

        public List<City> getCitiesByNationId(Guid nationId)
        {
            List<City> cities = getCities().Where(x => x.NationId == nationId).ToList();
            return cities;
        }

        public bool insertCity(City city)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.City cityEF = TOA.CityAssembler.DeAssembler(city);
                db.Cities.AddObject(cityEF);
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }
            return result;
        }

        public bool updateCity(City city)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.City cityEF = db.Cities.Where(x => x.IdCity == city.IdCity).FirstOrDefault();
                TOA.CityAssembler.WriteToEntity(cityEF, city);

                db.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }

            return result;
        }


        public bool deleteCity(City city)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.City cityEF = db.Cities.Where(x => x.IdCity == city.IdCity).FirstOrDefault();
                db.DeleteObject(cityEF);
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }

            return result;
        }
    }
}
